package com.huaji.learn.ui.dashboard;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.huaji.learn.R;
import com.huaji.learn.helper.NoteListAdapter;
import com.huaji.learn.model.NoteModel;
import com.huaji.learn.repository.NoteRepository;
import com.huaji.learn.ui.AddNoteActivity;

import java.util.List;

public class DashboardFragment extends Fragment {
    private RecyclerView recyclerView;
    private NoteListAdapter adapter;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        // 启用标题栏菜单
        setHasOptionsMenu(true);

        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);

        recyclerView = root.findViewById(R.id.recyclerView);
        // 设置 RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);

        // 创建适配器并设置给 RecyclerView
        adapter = new NoteListAdapter();
        recyclerView.setAdapter(adapter);

        NoteRepository repository = new NoteRepository(root.getContext());

        // 查询所有笔记
        List<NoteModel> itemDataList = repository.queryAllNotes();
        adapter.setItems(itemDataList);

        // 笔记项目单击事件
        adapter.setOnItemClickListener(note -> {
            navigateToAddPage(note.getId());
        });

        return root;
    }

    /**
     * 添加标题栏菜单
     * @param menu The options menu in which you place your items.
     *
     * @param inflater
     */
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.add_note_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    /**
     * 标题栏菜单单击事件
     * @param item The menu item that was selected.
     *
     * @return
     */
    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // 点击的是 添加 按钮
        if (item.getItemId() == R.id.btnAddNote) {
            navigateToAddPage(-1);
            return true;
        }
        else{
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 跳转到 添加/详情 页面
     * @param id
     */
    void navigateToAddPage(int id) {
        // 创建Intent对象
        Intent intent = new Intent(getActivity(), AddNoteActivity.class);

        intent.putExtra("ID", id);

        // 启动Activity
        startActivity(intent);
    }
}